package kr.hyunist.androidcomplete01saeildamil.ch19;

import kr.hyunist.androidcomplete01saeildamil.*;
import android.app.*;
import android.content.*;
import android.content.DialogInterface.OnClickListener;
import android.os.*;
import android.view.*;
import android.widget.*;

public class LongTimeEx04 extends Activity {
	int mValue;
	TextView mText;
	ProgressDialog mProgress;
	boolean mQuit;
	UpdateThread mThread;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.longtimeex);
		
		mText = (TextView) findViewById(R.id.longtimetv);
	}
	
	@SuppressWarnings("deprecation")
	public void mOnClick(View v){
		mValue = 0;
		showDialog(0);
		mQuit = false;
		mThread = new UpdateThread();
		mThread.start();
	}
	
	@SuppressWarnings("deprecation")
	@Override
	protected Dialog onCreateDialog(int id) {
		switch(id){
		case 0:
			mProgress = new ProgressDialog(this);
			mProgress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			mProgress.setTitle("Update");
			mProgress.setMessage("Wait...");
			mProgress.setCancelable(false);
			mProgress.setButton("Cancel", new OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					mQuit = true;
					dismissDialog(0);
					Toast.makeText(LongTimeEx04.this, "사용자에 의한 취소!", 0).show();
				}
				
			});
			return mProgress;
		}
		
		return null;
	}
	
	Handler mHandler = new Handler(){
		@SuppressWarnings("deprecation")
		public void handleMessage(Message msg) {
			mValue = msg.arg1;
			mText.setText(Integer.toString(mValue));
			
			if(mValue < 100){
				mProgress.setProgress(mValue);
			} else {
				mQuit = true;
				dismissDialog(0);
				Toast.makeText(LongTimeEx04.this, "업로드 완료!", 0).show();
			}
		};
	};
	
	class UpdateThread extends Thread {
		@Override
		public void run() {
			while(mQuit == false){
				mValue++;
				Message msg = mHandler.obtainMessage();
				msg.arg1 = mValue;
				mHandler.sendMessage(msg);
				
				try {
					Thread.sleep(50);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				
			}
		}
	}
}
